from flask import Blueprint, request, jsonify, current_app
from app.models.transactions import Transaction
from app.models.categories import Category
from app.extensions import db
from app.routes.auth import token_required
from datetime import datetime
import uuid
import os
from sqlalchemy.orm import joinedload  
transaction_bp = Blueprint('transaction', __name__)


# 1. 添加收支记录
@transaction_bp.route('', methods=['POST'])
@token_required
def add_transaction(current_user):
    data = request.get_json()
    # 必传参数
    type_ = data.get('type')
    category_id = data.get('category_id')
    category_name = data.get('categoryName')
    amount = data.get('amount')
    date = data.get('date')
    account = data.get('account', '默认账户')

    # 验证参数
    if type_ not in ['expense', 'income']:
        return jsonify({'success': False, 'message': '类型必须是expense或income'}), 400
    # 验证分类存在且名称匹配（不再检查user_id）
    category = Category.query.filter_by(id=category_id).first()
    if not category:
        return jsonify({'success': False, 'message': '分类不存在'}), 400
    if category.name != category_name:
        return jsonify({'success': False, 'message': '分类ID与名称不匹配'}), 400
    
    if not account or len(account) > 50:
        return jsonify({'success': False, 'message': '账户名称不能为空且长度不超过50'}), 400
    
    try:
        amount = float(amount)
        if amount <= 0:
            return jsonify({'success': False, 'message': '金额必须大于0'}), 400
    except:
        return jsonify({'success': False, 'message': '金额格式错误'}), 400
    
    try:
        date = datetime.fromisoformat(date.replace('Z', '+00:00'))  # 支持带Z的ISO格式
    except:
        return jsonify({'success': False, 'message': '日期格式错误（需ISO格式，如2024-01-15T12:00:00.000Z）'}), 400

    # 创建记录
    new_trans = Transaction(
        user_id=current_user.user_id,
        type=type_,
        category_id=category_id,
        account=account,
        amount=amount,
        remark=data.get('remark'),
        date=date
    )
    db.session.add(new_trans)
    db.session.commit()

    return jsonify({
        'success': True,
        'data': {
            'id': new_trans.id,
            'userId': new_trans.user_id,
            'type': new_trans.type,
            'categoryId': new_trans.category_id,
            'categoryName': category.name,
            'amount': float(new_trans.amount),
            'remark': new_trans.remark,
            'date': new_trans.date.isoformat().replace('+00:00', 'Z'),
            'createdAt': new_trans.created_at.isoformat().replace('+00:00', 'Z'),
            'updatedAt': new_trans.updated_at.isoformat().replace('+00:00', 'Z')
        },
        'message': '记录保存成功'
    }), 201


# 2. 查询收支记录（支持筛选）
@transaction_bp.route('', methods=['GET'])
@token_required
def get_transactions(current_user):
    # 筛选参数
    type_ = request.args.get('type')  # 可选：expense/income
    category_id = request.args.get('categoryId')  # 可选：分类ID
    start_date = request.args.get('startDate')  # 可选：开始日期
    end_date = request.args.get('endDate')  # 可选：结束日期
    page = int(request.args.get('page', 1))  # 分页
    per_page = int(request.args.get('perPage', 20))

    # 基础查询（关联分类表获取名称）
    query = Transaction.query.filter_by(user_id=current_user.user_id).options(
        joinedload(Transaction.category)  # 预加载分类信息，避免N+1问题
    )
    # 筛选条件
    if type_:
        query = query.filter_by(type=type_)
    if category_id:
        query = query.filter_by(category_id=category_id)
    if start_date:
        # 1. Start Date: 必须从 00:00:00 开始
        start_datetime_str = f"{start_date}T00:00:00"
        start_datetime = datetime.fromisoformat(start_datetime_str.replace('Z', '+00:00'))
        query = query.filter(Transaction.date >= start_datetime)
    if end_date:
        # 2. End Date: 必须到 23:59:59 结束
        end_datetime_str = f"{end_date}T23:59:59"
        end_datetime = datetime.fromisoformat(end_datetime_str.replace('Z', '+00:00'))
        query = query.filter(Transaction.date <= end_datetime)

    # 排序和分页
    query = query.order_by(Transaction.date.desc())
    pagination = query.paginate(page=page, per_page=per_page)
    transactions = pagination.items

    result = {
        'success': True,
        'data': {
            'total': pagination.total,
            'pages': pagination.pages,
            'currentPage': page,
            'items': []
        },
        'message': '查询成功'
    }

    for trans in transactions:
        result['data']['items'].append({
            'id': trans.id,
            'userId': trans.user_id,
            'type': trans.type,
            'categoryId': trans.category_id,
            'categoryName': trans.category.name,  # 从关联分类获取名称
            'amount': float(trans.amount),
            'remark': trans.remark,
            'date': trans.date.isoformat().replace('+00:00', 'Z'),
            'createdAt': trans.created_at.isoformat().replace('+00:00', 'Z'),
            'updatedAt': trans.updated_at.isoformat().replace('+00:00', 'Z')
        })

    return jsonify(result), 200


# 3. 编辑收支记录
@transaction_bp.route('/<int:trans_id>', methods=['PUT'])
@token_required
def update_transaction(current_user, trans_id):
    # 只能编辑自己的记录
    trans = Transaction.query.filter_by(id=trans_id, user_id=current_user.user_id).first()
    if not trans:
        return jsonify({'success': False, 'message': '记录不存在'}), 400

    data = request.get_json()
    # 更新字段
    if 'type' in data:
        trans.type = data['type']
    
    if 'categoryId' in data and 'categoryName' in data:
        # 验证分类（不再检查user_id）
        category = Category.query.filter_by(id=data['categoryId']).first()
        if not category:
            return jsonify({'success': False, 'message': '分类不存在'}), 400
        if category.name != data['categoryName']:
            return jsonify({'success': False, 'message': '分类ID与名称不匹配'}), 400
        trans.category_id = data['categoryId']
    
    if 'account' in data and data['account']:
        trans.account = data['account']
    
    if 'amount' in data:
        try:
            amount = float(data['amount'])
            if amount <= 0:
                return jsonify({'success': False, 'message': '金额必须大于0'}), 400
            trans.amount = amount
        except:
            return jsonify({'success': False, 'message': '金额格式错误'}), 400
    
    if 'remark' in data:
        trans.remark = data['remark']
    
    if 'date' in data:
        try:
            trans.date = datetime.fromisoformat(data['date'].replace('Z', '+00:00'))
        except:
            return jsonify({'success': False, 'message': '日期格式错误'}), 400

    db.session.commit()
    # 返回更新后的完整信息
    category = Category.query.get(trans.category_id)
    return jsonify({
        'success': True,
        'data': {
            'id': trans.id,
            'userId': trans.user_id,
            'type': trans.type,
            'categoryId': trans.category_id,
            'categoryName': category.name,
            'amount': float(trans.amount),
            'remark': trans.remark,
            'date': trans.date.isoformat().replace('+00:00', 'Z'),
            'createdAt': trans.created_at.isoformat().replace('+00:00', 'Z'),
            'updatedAt': trans.updated_at.isoformat().replace('+00:00', 'Z')
        },
        'message': '记录更新成功'
    }), 200


# 4. 删除收支记录
@transaction_bp.route('/<int:trans_id>', methods=['DELETE'])
@token_required
def delete_transaction(current_user, trans_id):
    trans = Transaction.query.filter_by(id=trans_id, user_id=current_user.user_id).first()
    if not trans:
        return jsonify({'success': False, 'message': '记录不存在'}), 400

    db.session.delete(trans)
    db.session.commit()
    return jsonify({'success': True, 'message': '记录已删除'}), 200